"""
@Author：WangYuXiang
@E-mile：Hill@3io.cc
@CreateTime：2021/4/22 17:00
@DependencyLibrary：无
@MainFunction：无
@FileDoc： 
    qr.py
    文件说明
@ChangeHistory:
    datetime action why
    example:
    2021/4/22 17:00 change 'Fix bug'
        
"""
from pathlib import Path

from sanic.response import file_stream
from tortoise.query_utils import Q

from common.accessory.models import AccessoryModel
from common.accessory.serializers import AccessoryLocalSerializer, AccessoryLocalListSerializer
from common.auth.models import UserModel
from common.auth.serializers import UserModelSerializer
from common.utils.authentication import verify_auth
from common.utils.permission import verify_prem
from common.utils.site_views import AdminSiteView
from srf.export_import_view import ExportImportView
from srf.status import HttpStatus


class AccessoryLocalViewSet(AdminSiteView):
    queryset = AccessoryModel
    serializer_class = AccessoryLocalListSerializer
    search_fields = ('@file_name', '@file_type')

    async def retrieve(self, request, *args, **kwargs):
        instance: AccessoryModel = await self.get_object()
        if instance.file_path is None:
            return self.error_json_response(msg='文件不存在', http_status=HttpStatus.HTTP_404_NOT_FOUND)
        if not Path(instance.file_path).exists():
            return self.error_json_response(msg='文件不存在', http_status=HttpStatus.HTTP_404_NOT_FOUND)
        return await file_stream(instance.file_path, filename=instance.file_original_name)

    @verify_auth()
    @verify_prem(['change_accessory'])
    async def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = await self.get_object()
        serializer = AccessoryLocalSerializer(
            instance, data=request.data, partial=partial, context={'request': request})
        await serializer.is_valid(raise_exception=True)
        await serializer.save()
        file = request.files.get('file')
        if file:
            await instance.change_file_to_loacl(request, file)
        return self.success_json_response(data=await serializer.data)

    @verify_auth()
    @verify_prem(['add_accessory'])
    async def create(self, request, *args, **kwargs):
        serializer = AccessoryLocalSerializer(
            data=request.data, context={'request': request})
        await serializer.is_valid(raise_exception=True)
        file = request.files.get('file')
        if not file:
            return self.error_json_response(data={'file': ['必须上传文件']}, msg='必须上传文件')
        await self.perform_create(serializer)
        return self.success_json_response(data=await serializer.data, http_status=HttpStatus.HTTP_201_CREATED)


# class A(ExportImportView):
#     queryset = UserModel
#     serializer_class = UserModelSerializer

#     export_header_title = {'id': '编号',
#                            'nickname': '昵称',
#                            'account': '账号',
#                            'phone': '电话',
#                            'login_datetime': '登录时间',
#                            'is_active': '是否激活',
#                            'is_super_admin': '超级管理员',
#                            'is_staff': '是否是员工'}

#     import_header_title = {
#         '昵称': 'nickname',
#         '账号': 'account',
#         '密码': 'password',
#         '电话': 'phone',
#         '是否激活': 'is_active',
#         '超级管理员': 'is_super_admin',
#         '是否是员工': 'is_staff'
#     }
